//
//  UITablewView+Ext.swift
//  
//
//  Created by 张崇超 on 2017/12/27.
//  Copyright © 2017年 zcc. All rights reserved.
//

import UIKit

var orininalFrame = "orininalFrame"
var imageView = "imageView"

extension UITableView {
    
    func setHeadView(frame: CGRect, superView: UIView) {
        
        
    }
    
    /// 设置表视图头视图 单张图片
    func setHeaderView(frame: CGRect, view: UIView?) {
        
        // 创建关联
        objc_setAssociatedObject(self, &orininalFrame, frame, .OBJC_ASSOCIATION_RETAIN)
        
        // 创建headerView
        let header = UIView.init(frame: frame)
        self.tableHeaderView = header
        
//        // 背景图片
//        let bgImg = UIImageView.init(frame: frame)
//        bgImg.image = iamgeView?.image
//        bgImg.contentMode = .scaleAspectFill
//        bgImg.clipsToBounds = true
//        self.insertSubview(bgImg, at: 0)
        
//        // 创建关联(image)
//        objc_setAssociatedObject(self, &imageView, bgImg, .OBJC_ASSOCIATION_RETAIN)
        
        // KVC监听
        self.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
    }
    
    open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        // 获取关联的对象
        let orginal = objc_getAssociatedObject(self, &orininalFrame) as? CGRect
        let img = objc_getAssociatedObject(self, &imageView) as? UIImageView
        
        // 偏移量
        let offset = self.contentOffset.y
        if offset < 0 {
            
            img?.frame = CGRect.init(x: offset, y: offset, width: (orginal?.size.width)!-2*offset, height: (orginal?.size.height)!-offset)
            
        } else {
            
            img?.frame = orginal!
        }
    }
}


